#include "stock.h"
#include <iostream>
Stock::Stock()
{
    company = "none name";
    shares = 0;
    shareValue = 0.0;
    totalValue = 0.0;
}

Stock::Stock(std::string name, int shares, double shareValue)
           :company(name),shares(shares),shareValue(shareValue){
    setTotal();
}

void Stock::buy(int shareAmount, double value) {
    if (shareAmount < 0)
    {
        std::cout << "Can not buy negative shares" << std::endl;
        shareAmount = 0;
    }
    shares += shareAmount;
    shareValue = value;
    setTotal();
}

void Stock::sell(int shareAmount ,double value) {
    if (shareAmount < 0)
    {
        std::cout << "Can not sell negative shares" << std::endl;
        shareAmount = 0;
    }
    shares -= shareAmount;
    shareValue = value;
    setTotal();
}

void Stock::setPrice(double price) {
    if (price < 0)
    {
        std::cout << "Share price can not set to negative value" << std::endl;
        return;
    }
    shareValue = price;
    setTotal();
}

//第一个const: 说明返回是值是const类型的
//第二个const: 说明参数是const的
//第三个cosnt: 说明这个方法中没有改变类中的属性值，比如一旦内部写了shareValue=10则会报错，见下文
const Stock & Stock::topValue(const Stock &aStock) const{
    if (aStock.totalValue > this->totalValue)
    {
        //重要：如果返回值不是const类型，那么这里就会报错，因为返回值改变了修饰aStock的const语义
        return aStock;
    }
    // !!!error: cannot assign to non-static data member within const member function 'topValue'
    // shareValue = 10;
    //重要：如果返回值不是const类型，那么这里就会报错，因为返回值改变了修饰该方法的const语义
    return *this;
}

//1. 设置浮点数以定点的方式展示
//2. 设置精度是3位
//3. 恢复设置
void Stock::show() const
{
    using std::cout;
    using std::endl;
    using std::ios_base;
    // 设置打印的模式
    ios_base::fmtflags initflags = cout.setf(ios_base::fixed, ios_base::floatfield);
    std::streamsize initPrecision = cout.precision(3);

    cout << "-------------------------------------------" << endl;
    cout << "company: " << company 
         << "\nshares: " << shares 
         << "\nshareValue: " << shareValue
         << "\ntotalValue: " << totalValue << endl;
    
    // 恢复之前的设置
    cout.setf(initflags);
    cout.precision(initPrecision);
    
}

Stock::~Stock()
{
    using namespace std;
    cout << "dealloc function is called" << endl;
}
 
void Stock::setTotal() {
    totalValue = shares * shareValue;
}
